package info.xinfu.carban.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hui.util.image.glide.GlideCircleTransform;
import com.hui.util.log.LogUtils;
import info.xinfu.carban.MyApp;
import info.xinfu.carban.R;
import info.xinfu.carban.base.BaseActivity;
import info.xinfu.carban.entity.UserEntity;
import info.xinfu.carban.utils.Constants;
import info.xinfu.carban.utils.SPUtils;
import com.vondear.rxtools.RxAppUtils;
import com.vondear.rxtools.RxNetUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.CookieStore;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;

//deviceId 登录时
public class LoginActivity extends BaseActivity {
    @BindView(R.id.img_logo)
    ImageView mImgLogo;
    //输入框,删除叉号,分割线,错误提示语
    @BindView(R.id.m_phone_edt)
    EditText m_phone_edt;
    @BindView(R.id.m_cancle)
    ImageView m_cancle;
    @BindView(R.id.m_phone_edt_bg)
    View m_phone_edt_bg;
    @BindView(R.id.m_phone_hint)
    TextView m_phone_hint;
    @BindView(R.id.m_pass_edt)
    EditText m_pass_edt;//面膜输入
    @BindView(R.id.m_look)
    ImageView m_look;//显示密码
    @BindView(R.id.m_pass_edt_bg)
    View m_pass_edt_bg;//分割线
    @BindView(R.id.m_pass_hint)
    TextView m_pass_hint;//密码错误提示语
    //登录按钮
    @BindView(R.id.btn_login)
    Button m_go_login;
    @BindView(R.id.tv_flag)
    TextView tv_flag;
    @BindView(R.id.ll_developed_by)
    LinearLayout llDevelopedBy;
    //操作登录控件状态
//    private LoginUtils mLoginUtils;
    //手机号,密码是否正确,是否显示密码
    private boolean mIsPhoneRight = false;
    private boolean mIsPasswordRight = false;
    private boolean mIsPasswordLook = false;
    private String deviceId_imei_;
    // TODO: 2017/11/20 version
    @BindView(R.id.tv_version)
    TextView tvVersion;

    @Override
    protected void initView() {
        // TODO: 2017/11/24 测试版本
        if (Constants.imgbase.contains(Constants.pot80)) {
            tv_flag.setVisibility(View.VISIBLE);
            tv_flag.setText("测试版");
        } else if (Constants.imgbase.contains("10.82.49.148")) {
            tv_flag.setVisibility(View.VISIBLE);
            tv_flag.setText("本地版");
        } else {
            tv_flag.setVisibility(View.GONE);
        }
        getOldUsrNameSet();
        Glide.with(mContext).load(R.mipmap.login_logo)
                .transform(new GlideCircleTransform(mContext))
                .crossFade()
                .into(mImgLogo);
        String versionName = RxAppUtils.getAppVersionName(mContext);
        tvVersion.setText("V" + versionName);

        /**
         * 得到设备id
         */
        /*AndPermission.with(this).requestCode(100)
                .permission(PermissionsConfig.PHONE)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
                        PermissionTipsDialog.getDefault().showRationalePermission(rationale, mContext);
                    }
                })
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        if (AndPermission.hasPermission(mContext, grantPermissions)) {
                            //执行方法
                            deviceId_imei_ = RxDeviceUtils.getDeviceId_IMEI_(mContext);
                        } else {
                            PermissionTipsDialog.getDefault().showNeverAskPermission(mContext);
                        }
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {

                        // 是否有不再提示并拒绝的权限。
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            PermissionTipsDialog.getDefault().showNeverAskPermission(mContext);
                        } else {
                            MyToastUtil.showNToast("拒绝设备id权限会导致无法绑定设备！！！");
                            //退出应用
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                }
                            }, 800);
                        }
                    }
                }).start();*/
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        getOldUsrNameSet();
        // TODO: 2017/11/24 测试版本
        if (Constants.imgbase.contains(Constants.pot80)) {
            tv_flag.setVisibility(View.VISIBLE);
            tv_flag.setText("测试版");
        } else {
            tv_flag.setVisibility(View.GONE);
        }
    }

    private void getOldUsrNameSet() {
        //获取之前的登录名 显示
        // TODO: 2017/12/1 改为使用工号登录
        String no = SPUtils.getString(Constants.username, "");
//        String oldUsrName = SPUtils.getString(Constants.username, "");
        if (!TextUtils.isEmpty(no)) {
            m_phone_edt.setText(no);
            mIsPhoneRight = true;
        }
        String pwd = SPUtils.getString(Constants.pwd, "");
//        String oldUsrName = SPUtils.getString(Constants.username, "");
        if (!TextUtils.isEmpty(pwd)) {
            m_pass_edt.setText(pwd);
        }
    }

    @OnClick({R.id.ll_kefu, R.id.btn_login, R.id.m_cancle, R.id.m_look})
    void onClick(View view) {
        switch (view.getId()) {

            case R.id.ll_kefu:

                break;
            case R.id.m_cancle:
                m_phone_edt.setText("");
                break;
            case R.id.m_look:
                if (mIsPasswordLook) {
                    //显示为密码****
                    m_pass_edt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    m_look.setImageResource(R.mipmap.icon_eye_close);
                } else {
                    //显示为文本
                    m_pass_edt.setInputType(TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    m_look.setImageResource(R.mipmap.icon_eye_open);
                }
                m_pass_edt.setSelection(m_pass_edt.getText().length());
                mIsPasswordLook = !mIsPasswordLook;
                break;
            case R.id.btn_login:
                if (RxNetUtils.isAvailable(mContext)) {
                    String username = m_phone_edt.getText().toString();
                    String pwd = m_pass_edt.getText().toString();
                    if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
                        doLogin(username, pwd);
                    }
                } else {

                    showNetErrorToast();
                }
                break;
//            case R.id.tv_forgetpwd:
//                act.startActivity(new Intent(act, ForgetPwdActivity.class));
//                break;
        }
    }

    private void doLogin(final String uname, final String pwd) {
        showPDialog();
     /*   deviceId_imei_ = RxDeviceUtils.getDeviceId_IMEI_(mContext);
        LogUtils.w(deviceId_imei_);*/
        SPUtils.putString(Constants.username, uname);
        SPUtils.putString(Constants.pwd, pwd);

        showToast("登陆成功");
        Intent intent = new Intent(mContext, CarMainActivity.class);
        //新任务
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        hidePDialog();
        finish();

/*

        OkHttpUtils.post().url(Constants.login)
                .addParams("userId", uname)
                .addParams("password", pwd)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //结束时别忘了hideDialog（）;
                        hidePDialog();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //结束时别忘了hideDialog;
                        hidePDialog();
                        LogUtils.e(response);
                        if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                            UserEntity userEntity = JSON.parseObject(response, UserEntity.class);
                            if (userEntity != null) {
                                //success
                                showToast("登陆成功");
                                Intent intent = new Intent(mContext, CarMainActivity.class);
                                //新任务
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                                finish();
                            } else {
                                //error
                                showToast("登录失败，请检查用户名和密码~");
                            }
                        } else {
                            //error
                            showToast("登录失败，请检查用户名和密码~");
                        }
                    }
                });
*/


    }

    @Override
    protected void setRootView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListen() {
//        mLoginUtils = new LoginUtils(mContext);
//        mLoginUtils.setPasswordListener(m_phone_edt, m_phone_hint, m_cancle, m_phone_edt_bg,
//                new LoginUtils.EditPhoneListener() {
//                    @Override
//                    public void isPhoneRight(boolean bool) {
//                        mIsPhoneRight = bool;
//                        isLogin();
//                    }
//                });
//        mLoginUtils.setPasswordListener(m_pass_edt, m_pass_hint, m_pass_edt_bg, m_look, new LoginUtils.EditPhoneListener() {
//            @Override
//            public void isPhoneRight(boolean bool) {
//                mIsPasswordRight = bool;
//                isLogin();
//            }
//        });
        m_phone_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    mIsPhoneRight = true;
                    isLogin();
                }
            }
        });
        m_pass_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    mIsPasswordRight = true;
                    isLogin();
                }
            }
        });

        /*llDevelopedBy.setOnClickListener(new View.OnClickListener() {
            final static int COUNTS = 5;//点击次数
            final static long DURATION = 1200;//规定有效时间
            long[] mHits = new long[COUNTS];

            @Override
            public void onClick(View v) {
                *//**
         * 实现双击方法
         * src 拷贝的源数组
         * srcPos 从源数组的那个位置开始拷贝.
         * dst 目标数组
         * dstPos 从目标数组的那个位子开始写数据
         * length 拷贝的元素的个数
         *//*
                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
//                    String tips = "您已在[" + DURATION + "]ms内连续点击【" + mHits.length + "】次了！！！";
//                    Toast.makeText(mContext, tips, Toast.LENGTH_SHORT).show();
                    LogUtils.w("点击api设置：" + mHits.length + "次");

                    View view_et_dialog = LayoutInflater.from(mContext).inflate(R.layout.view_edittext_dialog, null);

                    final EditText editText = (EditText) view_et_dialog.findViewById(R.id.et_et_dialog);
                    TextView tv_title = (TextView) view_et_dialog.findViewById(R.id.tv_dialog);
                    tv_title.setText(" ");
                    editText.setText("http://");
                    editText.setSelection(7);
                    editText.setImeOptions(IME_ACTION_DONE);
                    editText.setEms(TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    new AlertDialog.Builder(mContext)
                            .setNeutralButton("测试", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    SPUtils.putString("app_baseurl", "http://test.xinfu.info:8088/newerp");
                                    doExitApp();
                                }
                            }).setCancelable(false)
//                            .setMessage("默认为：http://oa.xinfu.info/newerp")
                            .setPositiveButton("本地", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
//                                    String result_et = editText.getText().toString();
//                                    if (!TextUtils.isEmpty(result_et)) {
                                    SPUtils.putString("app_baseurl", "http://10.82.49.148:8080/newerp");
//                                        SPUtils.putString("app_baseurl", result_et);
                                    doExitApp();
//                                    }
                                }
                            }).setNegativeButton("正式", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SPUtils.putString("app_baseurl", "http://oa.xinfu.info/newerp");
                            doExitApp();

                        }
                    }).setView(view_et_dialog).create().show();
                }
            }
        });*/
    }

    //清除Session
    public void doExitApp() {
        CookieJarImpl cookieJar = (CookieJarImpl) OkHttpUtils.getInstance().getOkHttpClient().cookieJar();
        CookieStore cookieStore = cookieJar.getCookieStore();
        cookieStore.removeAll();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                MyApp.getInstance().exit();
            }
        }, 500);
    }

    /**
     * 是否显示按钮状态
     */
    private void isLogin() {
        if (mIsPhoneRight && mIsPasswordRight) {
            m_go_login.setEnabled(true);
            m_go_login.setBackgroundResource(R.drawable.button_on);
        } else {
            m_go_login.setEnabled(true);
            m_go_login.setBackgroundResource(R.drawable.button_on);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        m_pass_edt = null;
        m_phone_edt = null;
        m_cancle = null;
        m_look = null;
        mImgLogo = null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
